package com.hy.memoryassistant;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

import java.util.List;

/**
 * Created by Mike on 08/03/2015.
 * This is the receiver to check for today's reminder
 * everyday. Currently, the interval is set for every
 * 1 day
 */
public class SchedulerReceiver extends BroadcastReceiver {
    private final String TAG = "SchedulerReceiver";
    private ReminderSQLCollection mCollection;
    private NotificationHelper mNotificationHelper;

    /**
     * On recieve method to check for today's reminders
     * TODO: update the next notification count and the next notification time
     *
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        // check for reminders
        if (mCollection == null)
            mCollection = ReminderSQLCollection.getInstance(context);

        if (mNotificationHelper == null)
            mNotificationHelper = new NotificationHelper(context);

        List<Reminder> reminders = mCollection.get(System.currentTimeMillis());

        Log.d(TAG, "# of Notifications: " + reminders.size());

        if (reminders.size() == 1) {
            mNotificationHelper.showReminder(reminders.get(0));
        } else if (reminders.size() > 1) {
            mNotificationHelper.showReminders(reminders);
        }

        wl.release();
    }

    /**
     * Sets scheduler to launch the intent everyday
     *
     * @param context
     */
    public void SetAlarm(Context context) {
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, SchedulerReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);

        Log.d(TAG, "Alarm set for every day");
        // for debugging, change the interval_day to 10000 for every 10 seconds
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), AlarmManager.INTERVAL_DAY, pi);
    }

    /**
     * Cancels the set alarm
     *
     * @param context
     */
    public void CancelAlarm(Context context) {
        Intent intent = new Intent(context, SchedulerReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }

}
